package com.sdx.common.utils;

import com.ibeetl.admin.core.util.UUIDUtil;
import com.sdx.service.ConfigService;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @ClassName FileUtils
 * @Description: 文件工具类
 * @author: tanbaocai
 * @date: 2018/7/31 16:06
 */
public class FileUtils {


	public static String getRoot() {
		return ConfigService.fileRoot;
	}

	public static boolean isEmptyFile(MultipartFile file) {
		return file.isEmpty() || file.getSize()==0;
	}

	/**
	 * 保存目录为root+subPath
	 * @param subPath 目录前缀，如/images/cover/20180801/contentid/
	 * @param file
	 * @return 返回实际文件名::原始文件名
	 */
	public static String upload(String subPath, MultipartFile file) throws IOException {
		String root = getRoot();
		String dir = root+subPath;
		File dirFile = new File(dir);
		if(!dirFile.exists()) {
			dirFile.mkdirs();
		}
		String originalFile = file.getOriginalFilename();
		int dotIdex = originalFile.lastIndexOf(".");
		String postfix = originalFile.substring(dotIdex);
		String fileName = UUIDUtil.uuid()+postfix;
		File target = new File(dirFile,fileName);
		file.transferTo(target);
		return fileName+"::"+originalFile;
	}

	public static void deleteFile(String filePath) {
		String root = getRoot();
		filePath = root+filePath;
		File file = new File(filePath);
		file.delete();
	}
	public static void main(String[] args) {
		File temp = new File("E://root/20180801/contentid1/");
		if (!temp.exists()) {
			temp.mkdirs();
		}
	}
}
